package com.niji.littly_donkey_android.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.*;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.niji.littly_donkey_android.R;
import com.niji.littly_donkey_android.adapter.BankCardAdapter;
import com.niji.littly_donkey_android.bean.BankCard;
import com.niji.littly_donkey_android.http.ConnectViaSession;
import com.niji.littly_donkey_android.util.JsonUtil;
import com.niji.littly_donkey_android.util.StatusBarUtil;
import com.niji.littly_donkey_android.util.UrlUtil;
import org.json.JSONException;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BillBillActivity extends BaseActivity {
    private static final String TAG = "BillBillActivity";

    private Button bill_bill_return;

    private RelativeLayout update_bank;

    private TextView bill_money;

    private TextView bill_bank_id;

    private TextView bill_bank_name;

    private Button bill_bill_submit;

    private static Double commissionRankMoney = 0.0;



    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bill_bill_activity);
        init();
        billBillReturn();
        updateBank();
        billSubmit();
    }

    /**
     * 提现
     */
    private void billSubmit() {
        bill_bill_submit = findViewById(R.id.bill_bill_submit);
        bill_bill_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int bankId = Integer.parseInt(bill_bank_id.getText().toString().trim());
                double amount = Double.parseDouble(bill_money.getText().toString().trim());
                String url = UrlUtil.URL + "/commission/withdraw?bank_id=" + bankId + "&amount=" + amount;
                RequestQueue requestQueue= Volley.newRequestQueue(BillBillActivity.this);
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        try {
                            Map<String, Object> map = JsonUtil.jsonToMap(s);
                            Integer code = (Integer) map.get("code");
                            if (code == 0) {
                                String data = (String) map.get("data");
                                Log.i(TAG,data);
                                Toast.makeText(BillBillActivity.this, data, Toast.LENGTH_LONG).show();
                                overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                                startActivity(new Intent(BillBillActivity.this,CommissionRankActivity.class));
                                finish();


                            } else if(code == -1){
                                Toast.makeText(BillBillActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                                overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                                Intent intent = new Intent(BillBillActivity.this, GetPhoneCodeActivity.class);
                                intent.putExtra("loginCode","-1");
                                startActivity(intent);
                                finish();
                            }else {
                                String data = (String) map.get("data");
                                Toast.makeText(BillBillActivity.this, data, Toast.LENGTH_SHORT).show();
                                overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                                finish();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
//
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e(TAG, volleyError.getMessage(), volleyError);
                    }
                }) {
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        String sesseionid = new ConnectViaSession(BillBillActivity.this).GetSession();
                        if (!sesseionid.equals("")) {
                            HashMap<String, String> headers = new HashMap<String, String>();
                            headers.put("cookie", sesseionid);
                            return headers;
                        } else {
                            return super.getHeaders();
                        }
                    }
                };

                requestQueue.add(stringRequest);
            }
        });
    }

    /**
     * 初始化页面
     */
    private void init() {
        bill_money = findViewById(R.id.bill_money);
        bill_bank_id = findViewById(R.id.bill_bank_id);
        bill_bank_name = findViewById(R.id.bill_bank_name);
        Intent intent = getIntent();
        String commissionRankMoney = intent.getStringExtra("commissionRankMoney");
        if ( commissionRankMoney != null){
            String[] s = commissionRankMoney.split("￥");
            this.commissionRankMoney = Double.parseDouble(s[1]);
        }
        BankCard bankCard = (BankCard) intent.getSerializableExtra("bankCard");
        bill_money.setText("" + this.commissionRankMoney);
        if (bankCard != null){
            bill_bank_id.setText("" + bankCard.getId());
            String name = bankCard.getName();
            String number = bankCard.getNumber();
            String substring = number.substring(number.length() - 4);
            String nameNum = name + "(" + substring + ")";
            bill_bank_name.setText(nameNum);
        }
        if (bankCard == null){
            //获取默认银行卡
            String url = UrlUtil.URL + "/commission/bank/card";
            RequestQueue requestQueue= Volley.newRequestQueue(BillBillActivity.this);
            StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    try {
                        Map<String, Object> map = JsonUtil.jsonToMap(s);
                        Integer code = (Integer) map.get("code");
                        if (code == 0) {
                            List<Map<String, Object>> mapList = (List<Map<String, Object>>) map.get("data");
                            Log.i(TAG,mapList.toString());
                            for (int i = 0; i < mapList.size(); i++) {
                                Integer id = (Integer) mapList.get(i).get("id");
                                String name = (String) mapList.get(i).get("name");
                                String number = (String) mapList.get(i).get("number");
                                Boolean is_default = (Boolean) mapList.get(i).get("is_default");
                                if(is_default){
                                    String substring = number.substring(number.length() - 4);
                                    String nameNum = name + "(" + substring + ")";
                                    bill_bank_name.setText(nameNum);
                                    bill_bank_id.setText("" + id);
                                    break;
                                }


                            }

                        } else if(code == -1){
                            Toast.makeText(BillBillActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(BillBillActivity.this, GetPhoneCodeActivity.class);
                            intent.putExtra("loginCode","-1");
                            startActivity(intent);
                            finish();
                        }else {
                            Toast.makeText(BillBillActivity.this, "银行卡列表获取失败", Toast.LENGTH_SHORT).show();
                            overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                            finish();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
//
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Log.e(TAG, volleyError.getMessage(), volleyError);
                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    String sesseionid = new ConnectViaSession(BillBillActivity.this).GetSession();
                    if (!sesseionid.equals("")) {
                        HashMap<String, String> headers = new HashMap<String, String>();
                        headers.put("cookie", sesseionid);
                        return headers;
                    } else {
                        return super.getHeaders();
                    }
                }
            };

            requestQueue.add(stringRequest);
        }

        RelativeLayout bill_loading = findViewById(R.id.bill_loading);
        RelativeLayout bill_main = findViewById(R.id.bill_main);
        bill_main.setVisibility(View.VISIBLE);
        bill_loading.setVisibility(View.INVISIBLE);


    }

    @Override
    protected int getLayoutId() {
        return R.layout.bill_bill_activity;

    }
    @Override
    protected int getStatusBarColor() {
        return R.color.white_easy_photos;
    }

    /**
     * 更改提现银行卡
     */
    private void updateBank() {
        update_bank = findViewById(R.id.update_bank);
        update_bank = findViewById(R.id.update_bank);
        update_bank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BillBillActivity.this, BillBankCardActivity.class);
                intent.putExtra("className","BillBillActivity");
                startActivity(intent);
                finish();
                   
            }
        });

    }

    /**
     * 返回事件
     */
    private void billBillReturn() {
        bill_bill_return = findViewById(R.id.bill_bill_return);
        bill_bill_return = findViewById(R.id.bill_bill_return);
        bill_bill_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                overridePendingTransition(R.anim.xpage_slide_in_left,R.anim.xpage_slide_out_right);
                finish();
            }
        });
    }

}
